﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;
using System.IO;
using System.Net;
using System.Text;

namespace WebsiteUI.Extensions
{
    public class HtmlWorkshop
    {
        // <summary>
        /// 清除html标签。
        /// </summary>
        /// <param name="orgin">要清除html标签的字符串。</param>
        /// <returns></returns>
        public static string ClearHtml(string orgin)
        {

            orgin = orgin.Replace("\r", "");
            orgin = orgin.Replace("\n", "");
            orgin = orgin.Replace("<br>", "");
            orgin = orgin.Replace("<BR>", "").Replace("&nbsp;", "").Replace("&nbsp", "");
            string m_pattern = @"<.*?>";
            Regex r = new Regex(m_pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
            MatchCollection mc = r.Matches(orgin);
            if (mc.Count > 0)
            {
                for (int i = 0; i < mc.Count; i++)
                {
                    string m_pattern2 = @"<[\\s]*>";
                    string group = mc[i].Groups[0].ToString();
                    if (null != group && ("<br>".Equals(group.ToLower()) || "<br/>".Equals(group.ToLower())))
                    { continue; }
                    Regex r2 = new Regex(m_pattern2, RegexOptions.Compiled | RegexOptions.IgnoreCase);
                    MatchCollection mc2 = r.Matches(group);
                    if (mc2.Count > 0)
                    {
                        for (int j = 0; j < mc2.Count; j++)
                        {
                            string rep = mc2[j].Groups[0].ToString();
                            orgin = orgin.Replace(rep, string.Empty);
                        }
                    }
                }
            }
            return orgin;
        }

        /// <summary>
        /// 除去所有在html元素中标记
        /// </summary>
        /// <param name="strhtml"></param>
        /// <returns></returns>
        public static string StripHtml(string strhtml)
        {
            string stroutput = strhtml;
            Regex regex = new Regex(@"<[^>]+>|</[^>]+>");
            stroutput = regex.Replace(stroutput, "");
            return stroutput;
        }

        public static string CutTitle(string title, int maxSize)
        {
            //Regex regex = new Regex("[a-zA-Z0-9]");
            //MatchCollection matches = regex.Matches(title);
            //int letterLen = (int)Math.Ceiling((double)matches.Count / 2);
            //// 判断大于maxSize个字符就截取字符串
            //if ((title.Length + letterLen > maxSize) && (title.Length >= maxSize + letterLen))
            //{ title = title.Substring(0, maxSize + letterLen) + "..."; }
            if (string.IsNullOrWhiteSpace(title))
            {
                return "";
            }
            title = StripHtml(ClearHtml(title)).Replace("&nbsp;", "").Replace("&#12288;", "").Replace(" ", "").Trim();
            int leng = title.Length;
            int totalLength = 0;
            int currentIndex = 0;
            while (totalLength < maxSize * 2 && currentIndex < leng)
            {
                if (title[currentIndex] < 0 || title[currentIndex] > 255)
                    totalLength += 2;
                else
                    totalLength++;
                currentIndex++;
            }
            if (currentIndex < leng)
            {
                title = title.Substring(0, currentIndex) + "...";
            }

            return title;
        }

        /// <summary>
        /// 输出相差日期
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string CheckTime(DateTime obj)
        {
            string time = "";
            DateTime timeNow = DateTime.Now;
            TimeSpan span = timeNow.Subtract(obj);
            double totaltime = span.TotalSeconds;
            var second = Math.Floor(totaltime % 60).ToString();
            var minite = Math.Floor((totaltime / 60) % 60).ToString();
            var hour = Math.Floor((totaltime / 3600) % 24).ToString();
            var day = Math.Floor((totaltime / 3600) / 24).ToString();
            if (int.Parse(day) > 3)
            {
                time = obj.ToString("yyyy-MM-dd");
            }
            else if (int.Parse(day) > 0)
            {
                time = day + "天前";
            }
            else if (int.Parse(hour) > 0)
            {
                time = hour + "小时" + minite + "分" + second + "秒前";
            }
            else if (int.Parse(minite) > 0)
            {
                time = minite + "分" + second + "秒前";
            }

            else if (int.Parse(second) > 5)
            {
                time = second + "秒前";
            }
            else
            {
                time = "刚刚";
            }
            return time;
        }

        /// <summary>
        /// 会员MemberID 加 部分*号
        /// </summary>
        /// <param name="memberId"></param>
        /// <returns></returns>
        public static string HideUserName(string memberId)
        {
            int length = memberId.Length;
            string username = "";
            if (length > 4)
            {
                username = memberId.Substring(0, length - 4) + "***" + memberId.Substring(length - 1);
            }
            else if (length >= 3)
            {
                username = memberId.Substring(0, length - 2) + "*" + memberId.Substring(length - 1);
            }
            else
            {
                username = memberId;
            }
            return username;
        }

        /// <summary>
        /// 获取中文星期
        /// </summary>
        /// <param name="time"></param>
        /// <param name="pre">可传来周或者星期或者其他</param>
        /// <returns></returns>
        public static string GetStrWeeks(DateTime time, string pre)
        {
            string week = time.DayOfWeek.ToString();
            string str = "";
            switch (week)
            {
                case "Monday":
                    str = pre + "一";
                    break;
                case "Tuesday":
                    str = pre + "二";
                    break;
                case "Wednesday":
                    str = pre + "三";
                    break;
                case "Thursday":
                    str = pre + "四";
                    break;
                case "Friday":
                    str = pre + "五";
                    break;
                case "Saturday":
                    str = pre + "六";
                    break;
                case "Sunday":
                    str = pre + "日";
                    break;
                default:
                    str = pre;
                    break;

            }
            return str;

        }


        /// <summary>
        /// 检查图片的类型
        /// </summary>
        /// <param name="obj"></param>
        /// <returns>true 正常</returns>
        public static bool CheckImgStyle(Object obj)
        {
            bool aa = false;
            string[] styleObj = new string[] { ".jpeg", ".jpg", ".gif", ".png", ".bmp" };
            foreach (string s in styleObj)
            {
                if (s == obj.ToString())
                {
                    aa = true;
                    break;
                }
                else
                    aa = false;
            }
            return aa;

        }

        /// <summary>
        /// 获取内容简介并关键字高亮(品牌)
        /// </summary>
        /// <param name="des"></param>
        /// <param name="MaxNum"></param>
        /// <param name="cont"></param>
        /// <param name="color"></param>
        /// <returns></returns>
        public static string GetCutDes(string des, int MaxNum, string cont, string color)
        {
            try
            {
                string[] strs = cont.Split(' ');
                string dess = StripHtml(ClearHtml(des)).Replace("&nbsp;", "");
                List<string> nstr = new List<string>();
                foreach (string str in strs)//处理数组空元素
                {
                    if (str != null && str != " " && str != "")
                    {
                        nstr.Add(str);
                    }
                }
                int prelength = 0;
                int i = 0;
                foreach (string st in nstr)//获取最前关键字下标
                {
                    if (i == 0 && dess.IndexOf(st) >= 0)
                    {
                        prelength = dess.IndexOf(st);
                        i = 1;
                    }
                    else
                    {
                        if (dess.IndexOf(st) < prelength && dess.IndexOf(st) >= 0)
                        {
                            prelength = dess.IndexOf(st);
                        }
                    }

                }

                string predes = dess.Substring(0, prelength);//获取关键字前面内容
                if (prelength > 30)
                {
                    predes = predes.Substring(0, 30) + "...";
                }
                dess = predes + dess.Substring(prelength);
                int leng = dess.Length;
                int totalLength = 0;
                int currentIndex = 0;
                while (totalLength < MaxNum * 2 && currentIndex < leng)
                {
                    if (dess[currentIndex] < 0 || dess[currentIndex] > 255)
                        totalLength += 2;
                    else
                        totalLength++;
                    currentIndex++;
                }
                if (currentIndex < leng)
                {
                    dess = dess.Substring(0, currentIndex) + "...";
                }

                foreach (string rstr in nstr)//改变关键字样式
                {
                    dess = dess.Replace(rstr, "<span style='color:" + color + ";'>" + rstr + "</span>");
                }
                return dess;
            }
            catch
            {
                return "";
            }
        }

        /// <summary>
        /// 获取客户端真实IP地址(可穿过代理服务器)
        /// </summary>
        /// <returns></returns>
        public static string ClientIP()
        {
            string result = String.Empty;

            result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (result != null && result != String.Empty)
            {
                //可能有代理 
                if (result.IndexOf(".") == -1)     //没有“.”肯定是非IPv4格式 
                    result = null;
                else
                {
                    if (result.IndexOf(",") != -1)
                    {
                        //有“,”，估计多个代理。取第一个不是内网的IP。 
                        result = result.Replace(" ", "").Replace("'", "");
                        string[] temparyip = result.Split(",;".ToCharArray());
                        for (int i = 0; i < temparyip.Length; i++)
                        {
                            if (IsIPAddress(temparyip[i]) && temparyip[i].Substring(0, 3) != "10." && temparyip[i].Substring(0, 7) != "192.168" && temparyip[i].Substring(0, 7) != "172.16.")
                            {
                                return temparyip[i];     //找到不是内网的地址 
                            }
                        }
                    }
                    else if (IsIPAddress(result)) //代理即是IP格式 
                        return result;
                    else
                        result = null;     //代理中的内容 非IP，取IP 
                }

            }

            string IpAddress = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null && HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != String.Empty) ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

            if (null == result || result == String.Empty)
                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

            if (result == null || result == String.Empty)
                result = HttpContext.Current.Request.UserHostAddress;

            return result;
        }

        #region bool IsIPAddress(str1) 判断是否是IP格式
        /// <summary>
        /// 判断是否是IP地址格式 0.0.0.0
        /// </summary>
        /// <param name="str1">待判断的IP地址</param>
        /// <returns>true or false</returns>
        public static bool IsIPAddress(string str1)
        {
            if (str1 == null || str1 == string.Empty || str1.Length < 7 || str1.Length > 15) return false;

            string regformat = @"^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$";

            Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);
            return regex.IsMatch(str1);
        }
        #endregion

        /// <summary>
        /// 记录客户登录请求的数据！
        /// </summary>
        //public static void ClientLoginMsg(string from, string memberid)
        //{
        //    string tip = ClientIP();
        //    string preSite = HttpContext.Current.Request.ServerVariables["Http_Referer"];//上一个链接
        //    string browerName = HttpContext.Current.Request.Browser.Browser;    //浏览器名称
        //    string browerVersion = HttpContext.Current.Request.Browser.Version; //浏览器版本       
        //    string os = Utils.GetClientOS();         //客户端操作系统

        //    string msg = from + " " + memberid + " " + tip + " " + DateTime.Now + " " + preSite + " " + browerName + " " + browerVersion + " " + os;
        //    string path = HttpContext.Current.Server.MapPath("/ClientMsg.txt");
        //    FileInfo fi1 = new FileInfo(path);
        //    if (!fi1.Exists)
        //    {
        //        //Create a file to write to.
        //        using (StreamWriter sw = fi1.CreateText())
        //        {
        //            sw.WriteLine(msg);
        //        }
        //    }
        //    else
        //    {
        //        using (StreamWriter sw = fi1.AppendText())
        //        {
        //            sw.WriteLine(msg);
        //        }
        //    }
        //}

        /// <summary>
        /// 会员MemberID 加 部分*号  加判空
        /// </summary>
        /// <param name="memberId"></param>
        /// <returns></returns>
        public static string HideUserMemberid(string memberId)
        {
            if (string.IsNullOrEmpty(memberId))
            {
                return string.Empty;
            }
            int length = memberId.Length;
            string username = "";
            if (length > 4)
            {
                username = memberId.Substring(0, length - 4) + "***" + memberId.Substring(length - 1);
            }
            else if (length >= 3)
            {
                username = memberId.Substring(0, length - 2) + "*" + memberId.Substring(length - 1);
            }
            else
            {
                username = memberId;
            }
            return username;
        }
    }
}